﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XH.SmartParking.Entities;

namespace XH.SmartParking.ORM
{
    public class XHDbContext : DbContext
    {
        public XHDbContext(DbContextOptions<XHDbContext> options)
             : base(options)
        { }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // EFCore的数据库执行日志，可以跟踪时使用
            //optionsBuilder.LogTo(Console.WriteLine);

            if (!optionsBuilder.IsConfigured)
                optionsBuilder.UseSqlServer("Data Source=LITTLESEAPAD;Initial Catalog=XHSmartParking;Persist Security Info=True;User ID=sa;Password=abc123;Trust Server Certificate=True");

            // 关于System.InvalidOperationException:“There is already an open DataReader associated with this Connection which must be closed first.”
            // 的异常处理：在连接字符串后添加“MultipleActiveResultSets=true”
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 联合主键
            modelBuilder.Entity<RoleMenu>()
                .HasKey(pk => new { pk.RoleId, pk.MenuId });
            modelBuilder.Entity<RoleUser>()
                .HasKey(pk => new { pk.RoleId, pk.UserId });
            // 角色表的一对多关系  角色对用户
            modelBuilder.Entity<RoleUser>()
                .HasOne(u => u.SysRole)
                .WithMany(r => r.Users)
                .OnDelete(DeleteBehavior.Cascade);
            modelBuilder.Entity<RoleMenu>()
                .HasOne(u => u.SysRole)
                .WithMany(r => r.Menus)
                .OnDelete(DeleteBehavior.Cascade);

            // 用户对角色
            modelBuilder.Entity<RoleUser>()
                .HasOne(u => u.User)
                .WithMany(r => r.Roles);


            // 页面-》数据库的转换
            // 数据库-》页面的转换
            ValueConverter iconValueConverter =
                new ValueConverter<string, string>(
                    p2d => string.IsNullOrEmpty(p2d) ? null : ((int)p2d.ToArray()[0]).ToString("x"),
                    d2p => d2p == null ? "" : ((char)int.Parse(d2p, NumberStyles.HexNumber)).ToString()
                    );
            modelBuilder.Entity<SysMenu>()
                .Property(m => m.MenuIcon)
                .HasConversion(iconValueConverter);
        }

        public virtual DbSet<SysUser> SysUser { get; set; }
        public virtual DbSet<SysMenu> SysMenu { get; set; }
        public virtual DbSet<SysRole> SysRole { get; set; }
        public virtual DbSet<RoleMenu> RoleMenu { get; set; }
        public virtual DbSet<RoleUser> RoleUser { get; set; }
        public virtual DbSet<DeviceInfo> DeviceInfo { get; set; }
        public virtual DbSet<AutoRegister> AutoRegister { get; set; }
        public virtual DbSet<BaseLicenseColor> BaseLicenseColor { get; set; }
        public virtual DbSet<BaseLicenseType> BaseLicenseType { get; set; }
        public virtual DbSet<BaseAutoColor> BaseAutoColor { get; set; }
        public virtual DbSet<BaseFeeMode> BaseFeeMode { get; set; }
        public virtual DbSet<MemberRecharge> MemberRecharge { get; set; }
        public virtual DbSet<RecordInfo> RecordInfo { get; set; }
        public virtual DbSet<OrderInfo> OrderInfo { get; set; }
    }
}
